import threading
import time

import PySimpleGUI as sg
import pandas as pd
import matplotlib.pyplot as plt
import webbrowser as web
import requests
from dataClassify import *
from CrawlCode import *
from WordCloud import *
from emoAnaly import *


# data = pd.read_csv("comment.csv", encoding='utf-8')
def getPosition(string, target):
    tmpposition = [i for i, char in enumerate(string) if char == target]
    return tmpposition[0]


# print(data)
# count=0
# def updateList(count):
# count = 5
list1 = []
list2 = []
no_lst = []
# 创建窗口布局
sg.theme('Tan')
# 首页菜单
menu = [
    ['选择&F', ['商品::-A-', '超链接::-B-']],
    ['退出&G', ['退出::-C-']]
]
# 商品页面
layouta = [
    # [sg.Image(filename='2.png')],
    # [sg.Menu(menu, size=(5, 5))],
    [sg.T('请输入要查询的天猫商品：')],
    [sg.In(key='-URL1-')],
    [sg.B('获取不同的商品链接'), sg.B('获取五个商品的评论')],
    [sg.LB(
        list1,
        # disabled=True,
        size=(70, 20),
        select_mode='simple',
        # enable_events=False,
        enable_events=True,
        key='-list1-')],
    [sg.T('第'), sg.Combo(no_lst, size=(10, 10), key='-URL2-'), sg.T('个商品'), sg.B('确定', key='-Y1-'),
     sg.B('打开网页', key='-Web1-'),
     sg.B('分析评论', key='-Ana1-')]
]
# 超链接页面
layoutb = [
    # [sg.Menu(menu, size=(5, 5))],
    [sg.T('请输入商品链接：')],
    [sg.In(key='-URL3-')],
    [sg.B('打开网页', key='-Web2-'), sg.B('分析评论', key='-Ana2-')]

]
# 分析页面
layoutc = [
    [sg.Menu(menu, size=(5, 5), key='-Mu2-')
        , sg.T('商品名称：', key='-Text01-')],
    [sg.T('什么颜色：'), sg.In(key='-Colr-')],
    [sg.T('字体大小：'), sg.In(key='-Font-')],
    [sg.B('词云展示', key='-Word-')],
    [sg.LB(
        list2,
        size=(70, 20),
        select_mode='simple',
        key='-list2-',
    )],
    [sg.B('词云分析', key='-Word2-'), sg.B('情感分析', key='-Emo-'),
     sg.B('数据分析', key='-Data-'), sg.B('返回', key='-Rern-')],
]
# 图片展示
layoutd = [
    [sg.Image(filename='', key='-Image1-'),sg.Image(filename='',key='-Image2-')],
    [sg.B('返回', key='-Rern2-')]
]
# 总页面
layouttotal = [
    [sg.Image(filename='首页.png'), sg.Menu(menu, size=(5, 5), key='-Mu1-'),
     sg.Frame(title='商品', layout=layouta, key='-Frame1-', visible=True),
     sg.Frame(title='超链接', layout=layoutb, key='-Frame2-', visible=False)
     ]
]
layout = [
    [sg.Frame(title='欢迎来到天猫商品评论分析APP', title_color='purple', font=50,
              layout=layouttotal, title_location='n', visible=True,
              key='-FrameT1-', relief='flat'),
     sg.Frame(title='商品评论分析', title_location='n', font=50,
              key='-FrameT2-', layout=layoutc, visible=False, relief='flat'),
     sg.Frame(title='图片展示', title_location='n', font=50,
              key='-FrameT3-', layout=layoutd, visible=False, relief='flat')
     ]
]

# 创建GUI窗口
window = sg.Window('天猫商品评论分析', layout, font='黑体')  # 修改图标 icon='ico.ico'

# 判断是否爬过链接
flag = False
# 爬取88链接存到List中
List = []
# 记录已经爬取评论的商品个数，每次加5
count = 0
# 获取第几条链接
var = 0
result = []
word_cloud_path = ''
freq_path = ''
while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    elif event == '获取不同的商品链接':  # 评论超链接显示处
        if values['-URL1-'] == '':
            sg.Popup('请输入商品！', font='黑体', text_color='red')
        else:
            List = crawlStep1(values['-URL1-'])
            # print(List)
            flag = True
            finalList = []
            for i in range(len(List)):
                finalList.append(str(i + 1) + '.' + List[i][1])
            window['-list1-'].update(
                values=finalList
            )
            print(values['-URL1-'])
    elif event == '获取五个商品的评论':
        if flag == False:
            sg.Popup('请输入商品！', font='黑体', text_color='red')
        else:
            crawlStep2(sg, List)
            count += 5
            LenList = []
            for i in range(count):
                LenList.append(str(i + 1))
            window['-URL2-'].update(
                values=LenList
                # no_lst=LenList
                # value=count
            )
            sg.Popup('成功获取五个商品的评论', font='黑体')
    elif event == '-Y1-':
        if flag == False:
            sg.Popup('请输入商品！', font='黑体', text_color='red')
        else:
            tmp = values['-list1-'][0]
            x = getPosition(tmp, '.')
            var = tmp[0:x]
            window['-URL2-'].update(
                value=var
            )
    elif event == '-Web1-':
        if flag == False:
            sg.Popup('请输入商品！', font='黑体', text_color='red')
        # values[]
        else:
            tmp1 = int(values['-URL2-'])
            if tmp1 > 88:
                sg.Popup('超过88个')
            else:
                web.open(List[tmp1 - 1][0])
    elif event == '-Y2-':
        break
    elif event == '商品::-A-':
        window['-Frame1-'].update(visible=True)
        window['-Frame2-'].update(visible=False)
    elif event == '超链接::-B-':
        window['-Frame1-'].update(visible=False)
        window['-Frame2-'].update(visible=True)
    elif event == '退出::-C-':
        eventtmp = sg.popup_ok_cancel('确定要退出吗？', title='提示', font='黑体')
        if eventtmp == 'OK':
            break
    elif event == '-Ana1-':
        if flag == False:
            sg.Popup('请输入商品！', font='黑体', text_color='red')
        elif count == 0:
            sg.Popup('未获取评论！', font='黑体', text_color='red')
        elif values['-URL2-'] == '':
            sg.Popup('未获取商品！', font='黑体', text_color='red')
        elif int(values['-URL2-']) > count:
            sg.Popup(f'当前商品位置超过{count}个！', font='黑体', text_color='red')
        else:
            window['-Text01-'].update(
                value='商品名称：' + values['-URL1-']
            )
            window['-FrameT1-'].update(visible=False)
            window['-FrameT2-'].update(visible=True)
            window['-FrameT3-'].update(visible=False)
        # window['-Mu1-'].update(disabled_items=[[0,0]])
        # window['商品::-A-'].update(values='!商品::-A-')

    elif event == '-Word-':
        if values['-Colr-'] == '':
            sg.Popup('请输入字体颜色！', font='黑体', text_color='red')
        elif values['-Font-'] == '':
            sg.Popup('请输入字体大小！', font='黑体', text_color='red')
        else:
            window['-FrameT1-'].update(visible=False)
            window['-FrameT2-'].update(visible=True)
            window['-FrameT3-'].update(visible=False)
            # 显示状态指示器或进度条等控件，提示正在生成词云图
            progress_bar = sg.ProgressBar(100, orientation='h', size=(20, 20), key='-PROG-')
            progress_bar.UpdateBar(0)
            # 创建一个线程来运行生成词云图的操作
            thread = threading.Thread(target=generate_word_cloud_threaded,
                                      args=("comment.csv", "stopwords.txt", int(values['-URL2-']),
                                            "wordcloud-result", 100, "./typeface/SourceHanSans-Regular.otf",
                                            1600, 2400, 3, "RGBA", '#252525', values['-Colr-'], int(values['-Font-']), 42, update_gui))
            thread.start()

            # 在主线程中等待线程结束
            while thread.is_alive():
                event, values = window.read(timeout=100)

                # 更新进度条或状态指示器等控件
                progress_bar.UpdateBar(thread.progress * 100)

                if event == sg.WIN_CLOSED:
                    thread.join()
                    break
    elif event == '-Rern-':
        window['-FrameT1-'].update(visible=True)
        window['-FrameT2-'].update(visible=False)
        window['-FrameT3-'].update(visible=False)
    elif event == '-Word2-':
        if (word_cloud_path == '') or (freq_path == ''):
            sg.Popup('未获取词云！', font='黑体', text_color='red')
        else:
                # filetmp = r'wordcloud-result\1-'
            window['-Image1-'].update(
                filename=word_cloud_path
            )
            window['-Image2-'].update(
                filename=freq_path
            )
            window['-FrameT1-'].update(visible=False)
            window['-FrameT2-'].update(visible=False)
            window['-FrameT3-'].update(visible=True)
    elif event == '-Data-':
        window['-Image1-'].update(
            filename=month_analyze(List[values['-URL2-']-1][1], sg)
        )
        window['-Image2-'].update(
            filename=count_analyze(List[values['-URL2-']-1][1], sg)
        )
        window['-FrameT1-'].update(visible=False)
        window['-FrameT2-'].update(visible=False)
        window['-FrameT3-'].update(visible=True)
    elif event == '-Emo-':
        window['-Image1-'].update(
            filename=emotion()
        )
        window['-Image2-'].update(
            filename=''
        )
        window['-FrameT1-'].update(visible=False)
        window['-FrameT2-'].update(visible=False)
        window['-FrameT3-'].update(visible=True)
    elif event == '-Rern2-':
        window['-FrameT1-'].update(visible=False)
        window['-FrameT2-'].update(visible=True)
        window['-FrameT3-'].update(visible=False)
    # window['-Frame1-'].update(visible=False)
    # window['-Frame2-'].update(visible=False)
    # window['-Frame3-'].update(visible=True)
    # elif event1 == '-No-':
    #     window = sg.Window('天猫商品评论分析', layouta, font='黑体')  # 修改图标 icon='ico.ico'
    # elif event1 == '退出::-C-':

    # window = sg.Window('提示', layoutc, font='黑体')  # 修改图标 icon='ico.ico'
# elif event == '打开网页':

# webbrowser.open_new('https://blog.csdn.net/weixin_42332345/article/details/106120919')
# print(values)
# print('获取商品链接成功')
# print(f'一共获取到{5}条链接')
# url = values['-URL-']

# elif event == '分析评论':
#         print('请先获取评论')


window.close()
